package com.nbcb.nwql.applicantion.api;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jd.platform.async.executor.Async;
import com.jd.platform.async.wrapper.WorkerWrapper;
import com.nbcb.nwql.applicantion.domain.ImageDataExportVo;
import com.nbcb.nwql.applicantion.domain.MyExcelImport;
import com.nbcb.nwql.applicantion.domain.UserLogInRq;
import com.nbcb.nwql.applicantion.util.ParWorker;
import com.nbcb.nwql.common.excel.ImportListenUtil;
import com.nbcb.nwql.common.rtnvo.ApiResponse;
import com.nbcb.nwql.common.util.CommonUtil1;
import com.nbcb.nwql.glowbal.annotation.RecordLogsAspectAt;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Supplier;

@RestController
@RequestMapping("pc")
@Slf4j
public class T20230308Api {
    @Autowired
    private MemcachedClient memcachedClient;

    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 测试异常
     * @return 返回统一封装信息
     */
    @GetMapping("/test")
    @RecordLogsAspectAt
    public ApiResponse testController() {
        log.info("进入到异常测试");
        //int num = 1 / 0;
        return ApiResponse.ok("调用成功");
    }

    /***
     * 测试缓存
     * @return
     * @throws InterruptedException
     * @throws MemcachedException
     * @throws TimeoutException
     */
    @GetMapping("/xmemCached")
    @RecordLogsAspectAt
    public ApiResponse testMemcached() throws InterruptedException, MemcachedException, TimeoutException {
// 放入缓存
        boolean flag = memcachedClient.set("a", 0, 1);

        // 取出缓存
        Object a = memcachedClient.get("a");
        log.warn("a is [{}]", a);

        // 3s后过期
        memcachedClient.set("b", 3, 2);
        Object b = memcachedClient.get("b");
        log.warn("b is [{}]", b);

        Thread.sleep(3000);
        b = memcachedClient.get("b");
        log.warn("b is [{}]", b);
        log.warn("a is [{}] 3s后", a);

        return ApiResponse.ok("调用成功");
    }

    /***
     * 测试redis
     */
    @GetMapping("/redis")
    @RecordLogsAspectAt
    void redis() {
        redisTemplate.opsForValue().set("myNm", "我是一颗卷心菜");
        String name = (String) redisTemplate.opsForValue().get("myNm");
        log.info("redis测试卷心菜，结果为:{}", name); //卷心菜
    }

    /***
     * 测试redis
     */
    @GetMapping("/redisDX")
    @RecordLogsAspectAt
    void redisDX() {
        ObjectMapper objectMapper = new ObjectMapper();
        UserLogInRq userLogInRq = new UserLogInRq();
        userLogInRq.setLogId("17843960420");
        userLogInRq.setPassword("nbcb,111");
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(userLogInRq);

            redisTemplate.opsForValue().set("17843960420UserLogInfo", jsonStr);
            String userLogInRqStr = (String) redisTemplate.opsForValue().get("17843960420UserLogInfo");

            UserLogInRq userLogInRqTrans = objectMapper.readValue(userLogInRqStr, UserLogInRq.class);
            log.info("redis测试对象存储转换，结果为:{}", userLogInRqTrans);

        } catch (JsonProcessingException jsonProcessingException) {
            log.info("错误1——————————————");
        } catch (IOException ioException) {
            log.info("错误2——————————————");
        }

    }

    /***
     * test   测试list上限
     */
    //@GetMapping("/testMaxArrayList")
    //@RecordLogsAspectAt
    static void testMaxArrayList() {
        ArrayList<Object> objects = new ArrayList<>();
        int num = 0;
        while (true) {
            num++;
            objects.add("1");
            if (num >= 2147483647) {
                log.info("当前数组大小：{}", objects.size());
            }
        }

    }

    /***
     * test   测试list上限
     */
    @GetMapping("/testImagesExport")
    @RecordLogsAspectAt
    public ApiResponse testImagesExport() throws MalformedURLException {
        String fileName = "C:\\Users\\40249\\Desktop\\export\\exp\\image.xlsx";
        String path = "C:\\Program Files (x86)\\Steam\\steamapps\\workshop\\content\\431960\\819750546\\pic\\lks.jpg";

        ArrayList<ImageDataExportVo> list = new ArrayList<>();

        ImageDataExportVo imageData = new ImageDataExportVo();
        //imageData.setFiles(new File(path));
        list.add(imageData);

        EasyExcel.write(fileName, ImageDataExportVo.class).sheet().doWrite(list);
        return ApiResponse.ok("导出成功");
    }

    /***
     * test   测试list上限
     */
    @PostMapping("/testImagesImport")
    @RecordLogsAspectAt
    public ApiResponse testImagesImport(MultipartFile file) throws IOException {

        List<MyExcelImport> myExcelImports = new ArrayList<>();
        ImportListenUtil importListenUtil = new ImportListenUtil(myExcelImports);

        EasyExcel.read(file.getInputStream(), MyExcelImport.class, importListenUtil)
        .headRowNumber(1)
        .sheet()
        .doRead();
        System.out.println("导入图片成功，解析数组为: " + importListenUtil.getMyExcelImports());
        return ApiResponse.ok("导入成功");
    }

    /***
     * test   测试list上限
     */
    @PostMapping("/testImagesImport1")
    @RecordLogsAspectAt
    public static ApiResponse testCompleteFuture() throws IOException, ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(6);
        Supplier task1 = new task1();
        Runnable task2 = new task2();
        Runnable task3 = new task3();
        CompletableFuture<String> task = CompletableFuture.supplyAsync(task1,pool);
        System.out.println(task.get());
        task.thenRunAsync(task2,pool).thenRunAsync(task3,pool);

        return ApiResponse.ok("执行成功");
    }

    static class task1 implements  Supplier {
        /**
         * Gets a result.
         *
         * @return a result
         */
        @Override
        public Object get() {
            return "执行顺序1";
        }
    }

    static class task2 implements Runnable{

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            System.out.println("执行顺序2");
        }
    }

    static class task3 implements Runnable{

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            System.out.println("执行顺序3");
        }
    }

    /***
     * test   测试list上限
     */
    @PostMapping("/testAsync")
    @RecordLogsAspectAt
    public static ApiResponse testAsync() throws IOException, ExecutionException, InterruptedException {


        ParWorker w = new ParWorker();
        ParWorker w1 = new ParWorker();
        ParWorker w2 = new ParWorker();

        WorkerWrapper<String, String> workerWrapper2 =  new WorkerWrapper.Builder<String, String>()
                .worker(w2)
                .callback(w2)
                .param("2")
                .build();

        WorkerWrapper<String, String> workerWrapper1 =  new WorkerWrapper.Builder<String, String>()
                .worker(w1)
                .callback(w1)
                .param("1")
                //.next(workerWrapper2)
                .build();

        WorkerWrapper<String, String> workerWrapper =  new WorkerWrapper.Builder<String, String>()
                .worker(w)
                .callback(w)
                .param("0")
                .build();

        System.out.println("执行开始：" + CommonUtil1.sdf2414.format(new Date()));

        Async.beginWork(1500, workerWrapper, workerWrapper1, workerWrapper2);

        System.out.println("执行结束：" + CommonUtil1.sdf2414.format(new Date()));

        System.out.println("ThreadCount："+Async.getThreadCount());

        System.out.println("WorkResult："+workerWrapper.getWorkResult());
        Async.shutDown();
        return ApiResponse.ok("导入成功");
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        testCompleteFuture();
    }

}
